package logic

import (
	"context"
	"strconv"
	"yuekaoHouse/api/pkg"
	"yuekaoHouse/house_srv/house"

	"yuekaoHouse/api/internal/svc"
	"yuekaoHouse/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginByMobileCodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginByMobileCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginByMobileCodeLogic {
	return &LoginByMobileCodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginByMobileCodeLogic) LoginByMobileCode(req *types.LoginByMobileCodeRequest) (resp *types.RegMsgResponse, err error) {
	// todo: 手机号短信验证码登录

	//判断手机号格式
	boo := pkg.MobileType(req.Mobile)
	if boo == false {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "手机号格式错误",
			Data: nil,
		}, nil
	}
	//短信验证码效验
	code, err := l.svcCtx.HouseSrv.GetSmsCode(l.ctx, &house.GetSmsCodeRequest{
		Mobile: req.Mobile,
		Sale:   "login",
	})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "服务器错误",
			Data: nil,
		}, err
	}
	if code.Code != req.Coed {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "验证码错误",
			Data: nil,
		}, err
	}
	//销毁
	_, err = l.svcCtx.HouseSrv.DelSmsCode(l.ctx, &house.DelSmsCodeRequest{
		Mobile: req.Mobile,
		Sale:   "login",
	})
	if err != nil {
		return nil, err
	}

	//登录 （判断手机号是否存在）
	mobileCode, err := l.svcCtx.HouseSrv.LoginByMobileCode(l.ctx, &house.LoginByMobileCodeRequest{
		Mobile: req.Mobile,
	})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -3,
			Mag:  "服务器错误",
			Data: nil,
		}, err
	}
	if mobileCode.UserID == 0 {
		return &types.RegMsgResponse{
			Cre:  -3,
			Mag:  "登录失败，手机号不存在",
			Data: nil,
		}, err
	}
	//生成token
	token, err := pkg.GetJwtToken(strconv.FormatInt(mobileCode.UserID, 10))
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -4,
			Mag:  "生成token失败",
			Data: nil,
		}, err
	}
	return &types.RegMsgResponse{
		Cre: 0,
		Mag: "登录成功",
		Data: map[string]interface{}{
			"Token": token,
		},
	}, err
}
